<template>
	<view>
		<view style="background-color: #1590EF">
			<u-tabs style="width: 90%;margin:0 5%;" :list="list1" @click='tabsClick' lineWidth="40" lineHeight="6"
				lineColor="#fff" :activeStyle="{
		    color: '#fff',
		    fontWeight: 'bold',
		    transform: 'scale(1.05)'
		}" :inactiveStyle="{
			 color: '#DFF1FE',
		}"></u-tabs>
		</view>
		<view v-if="activeName!=='检查记录维护'">
			<view class="progressBar">
				<u-line-progress style="width: 80%;display: inline-block;" :percentage="(present/amount)*100"
					activeColor="#217FFF" :showText="false"></u-line-progress>
				<text style="display: inline-block;margin: 0 20rpx;font-size: 25rpx;">{{present}}/{{amount}}</text>
			</view>
			<view v-if="updateView">
				<view class="topic" v-for="(item,index) in tableDataList" :key="item.id">
					<view style="position: relative;">
						<view class="topic_index">{{index+1}}</view>
						<text style="width: 86%;display:inline-block;margin: 0 0 0 75rpx;">{{item.inspItemName}}</text>
					</view>
					<view v-for="(items,i) in item.inspResult" :key='i'>
						<u-radio-group v-model="items.checked" size='30' style='margin:35rpx 0;' @change='radioChange'>
							<view v-for="(radio,d) in  items.children" :key="d" style="width: 100%;">
								<u-radio activeColor="#1590EF" labelSize='30' :label="radio.dictValue"
									:name='radio.dictKey' style='width: 45%;padding: 10rpx;'>
								</u-radio>
							</view>

							<image src="/static/dailySupervision/more.png"
								style="width: 10rpx;height: 45rpx;display: inline-block;" @click="moreClick(index)"></image>
						</u-radio-group>
					</view>

					<view style="display: inline-block;width: 100%;" v-for="key in item.inspRecord">
						<text style="padding:0 0 0 10rpx;font-size: 26rpx;display: inline-block;">
							{{key.dictValue}}</text>
						<u--input v-model="key.blankValue " border="bottom" clearable
							style='display: inline-block;width: 30%;'>
						</u--input>
					</view>
				</view>
			</view>


		</view>
		<!-- 检查结果记录 -->
		<view v-else style="padding: 0 0 50px 0;">
			<view class="topic" v-for="(item,index) in lastTableData">
				<!-- <text class="topic_title">安全生产不合格项</text> -->
				<view style="position: relative;">
					<view class="topic_index">{{index+1}}</view>
					<text style="width: 86%;display:inline-block;margin: 0 0 0 75rpx;">{{item.inspItemName}}</text>
				</view>
				<view v-for="(items,i) in item.inspResult">
					<u-radio-group v-model="items.checked" size='30' style='margin:35rpx 0;'>
						<view v-for="(radio,i) in  items.children" :key="i" style="width: 100%;">
							<u-radio :disabled="true" activeColor="#1590EF" labelSize='30' :label="radio.dictValue"
								:name='radio.dictKey' style='width: 45%;padding: 10rpx;'>
							</u-radio>
						</view>
					</u-radio-group>
				</view>
				<view style="display: inline-block;width: 100%;" v-for="key in item.inspRecord">
					<text style="padding:0 0 0 10rpx;font-size: 26rpx;display: inline-block;"> {{key.dictValue}}</text>
					<u--input v-model="key.blankValue " border="bottom" clearable
						style='display: inline-block;width: 30%;' :disabled="true">
					</u--input>
				</view>
			</view>
			<view class="topic_trouble">
				<u--form labelPosition="left" :model="recordList" :rules="rules" ref="recordList">
					<text class="topic_title">是否存在安全隐患</text>
					<u-form-item prop="isRisks" borderBottom @click="showDate = true;">
						<u-radio-group v-model="recordList.isRisks" size='30' style='margin:35rpx 0;'>
							<u-radio activeColor="#1590EF" labelSize='30' label="是" name='1'
								style='width: 45%;padding: 10rpx;'>
							</u-radio>
							<u-radio activeColor="#1590EF" labelSize='30' label="否" name='0'
								style='width: 45%;padding: 10rpx;'>
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<text class="topic_title">核查记录时间</text>
					<u-form-item prop="inspTime" borderBottom @click="showDate = true;">
						<uni-datetime-picker :show="showDate" @close='showDate = false;' v-model="recordList.inspTime"
							type="date" :clear-icon="false" />
					</u-form-item>
					<text class="topic_title ">安全隐患说明</text>
					<u-form-item prop="risksExplain" borderBottom>
						<u--textarea v-model="recordList.risksExplain" height='200'></u--textarea>
					</u-form-item>
					<text class="topic_title ">检查记录附件</text>
					<u-form-item prop="file" borderBottom>
						<view class="file-list clearfix">
							<view class="file-item" v-for="(item,index) in recordList.files">
								<image class="file-img" :src="item.temp" mode="aspectFit"></image>
								<view class="file-del" @click="fileDel(index)"></view>
							</view>
							<view class="file-item file-upload-btn" @click="selectFile"></view>
						</view>
					</u-form-item>
				</u--form>
			</view>
		</view>
		<view>
			<u-button type="primary" size="large" :text="activeName=='检查记录维护'?'提交':'保存本页面'" shape="circle"
				class='submit' @click='submitClick()'>
			</u-button>
		</view>
	</view>
</template>

<script>
	import * as api from '@/common/api/danger.js'
	import {
		deepClone,
		formDataInit
	} from '@/common/util.js'

	export default {
		components: {},
		data() {
			return {
				list1: [],
				radioValue: "",
				radioValue1: "",
				present: 0,
				amount: 0,
				activeName: "",
				recordList: {
					inspTime: "",
					risksExplain: "",
					files: [],
					isRisks:""
				},
				files: [],
				showDate: false,
				rules: {
					'risksExplain': {
						type: 'string',
						required: true,
						message: '请填写安全隐患说明',
						trigger: ['blur', ]
					},
					'inspTime': {
						type: 'string',
						required: true,
						message: '请选择检查时间',
						trigger: ['change','blur' ]
					},
					'isRisks': {
						type: 'string',
						required: true,
						message: '请选择是否有安全隐患',
						trigger: ['change', ]
					},

				},
				fileList: [],
				options: {},
				tableData: {},
				tableDataList: {},
				lastTableData: {},
				lastShow: false,
				carNum: 0, //运输车辆
				updateView: false
			}
		},
		onLoad(option) {
			this.options = option
		},
		mounted() {
			this.search(1)
		},
		watch: {
			activeName(activeName) {
				if (activeName === "检查记录维护") {
					this.view_insp_result();
				}
			},
		},
		methods: {
			search(item) {
				this.list1 = []
				api.default.getCheckTaskDetails({
					taskId: this.options.taskId
				}).then(res => {
					this.tableData = res.data.data
					if (this.tableData.safetyProd.length != 0) {
						let aTable = this.initTable(this.tableData.safetyProd)
						this.list1.push({
							name: "隐患排查",
							key: "safetyProd",
							aTable,
							status: this.isCompleted(aTable),
						});
					}
					// 默认选中
					if (item == 1) {
						this.activeName = this.list1[0].name
						this.tabsClick({
							name: this.list1[0].name,
							index: 0,
						})
						this.updateLastStatus()
					}
				})


			},

			view_insp_result() {
				api.default.getCheckTaskMaintain({
					taskId: this.options.taskId
				}).then(rst => {
					const resData = rst.data.data.noStandard;
					this.lastTableData = this.initTable(resData);
				})
			},

			// 检查记录维护
			tabsClick(item) {
				this.updateView = false
				this.activeName = item.name
				if (item.index == 0) {
					this.safetyBar()
				}
			},

			// 更多
			// moreClick(i) {
			// 	const moreData = {
			// 		enforcementBasis: this.tableDataList[i].enforcementBasis, //处罚依据
			// 		punishmentBasis: this.tableDataList[i].punishmentBasis, //执法依据
			// 		inspStandard: this.tableDataList[i].inspStandard, //检查标准
			// 		coMaterials: this.tableDataList[i].coMaterials, //企业上传材料
			// 		inspMethod: this.tableDataList[i].inspMethod, //检查方法
			// 	}
			// 	this.$goBack('./projectDetails?moreData=' + encodeURIComponent(JSON.stringify(moreData)), 2);
			// },

			//提交
			submitClick() {
				const save_record = {
					'safetyProd': api.default.safeKeepSave,
				}
				if (this.activeName !== '检查记录维护') {
					let saveItem = this.list1.find((item) => item.name == this.activeName);
					let itemStatus = true;
					const formData = this.tableDataList.map((item) => {
						const inspOpt = [],
							inspBlank = [];
						item.inspResult.forEach((obj) => {
							if (obj.checked === "") {
								itemStatus = false; // 当前页状态；信息是否勾选完整
							} else {
								inspOpt.push({
									key: obj.checked,
								});
							}
						});
						item.inspRecord.map((obj) => {
							if (obj.blankValue === "") {
								// itemStatus = false; // 当前页状态；信息是否勾选完整
							} else {
								inspBlank.push({
									key: obj.dictKey,
									value: obj.blankValue,
								});
							}
						});
						return {
							inspItemId: item.id,
							inspOpt,
							inspBlank,
						};
					});

					save_record[saveItem.key](this.options.taskId, formData).then(res => {
						uni.showToast({
							title: '保存成功',
							icon: 'none',
							duration: 2000
						})
						saveItem.status = itemStatus;
						this.updateLastStatus()


					})

				} else {
					this.$refs.recordList.validate().then(res => {
						const formData = this.recordList;
						formData.taskId = this.options.taskId;
						api.default.inspectionSave(formData).then(() => {
							uni.showToast({
								title: '提交成功！',
								icon: 'none',
								duration: 2000
							})
						});
						this.$goBack('./checkTask', 5)
					})
				}
			},

			//更新进度条
			radioChange() {
				this.carNum = 0
				this.amount = this.tableDataList.length
				this.tableDataList.map(item => {
					let aNum = 0
					item.inspResult.forEach(items => {
						if (items.checked !== "") {
							aNum++
						}
					})
					if (item.inspResult.length == aNum) {
						this.carNum++
					}
				})
				this.present = this.carNum
			},

			//重新请求进度条
			safetyBar() {
				api.default.getCheckTaskDetails({
					taskId: this.options.taskId
				}).then(res => {
					this.tableDataList = this.initTable(res.data.data.safetyProd);
					this.prodNum = 0
					this.amount = this.tableDataList.length
					this.tableDataList.map(item => {
						let aNum = 0
						item.inspResult.forEach(items => {
							if (items.checked !== "") {
								aNum++
							}
						})
						if (item.inspResult.length == aNum) {
							this.prodNum++
						}
					})
					this.present = this.prodNum
					this.updateView = true
				})
			},

			// 更新最后一页的动态
			updateLastStatus() {
				const that = this
				let lastShow = true;
				this.list1.forEach((item) => {
					if (!item.status) {
						lastShow = false;
					}
				});
				this.lastShow = lastShow;
				if (this.lastShow) {
					let arr = []
					this.list1.forEach(item => {
						arr.push(item.name)
					})
					if (!arr.includes('检查记录维护')) {
						this.list1.push({
							name: "检查记录维护"
						})
					}
				}
			},

			// 点击选择图片
			selectFile() {
				if (this.recordList.files.length == 9) {
					uni.showToast({
						title: "最多上传9个",
						icon: 'none'
					})
					return;
				}
				uni.chooseImage({
					count: 9 - this.recordList.files.length,
					success: (chooseImageRes) => {
						// console.log(chooseImageRes)
						uni.uploadFile({
							url: '/data-inspection-study/insp_file/upload',
							filePath: chooseImageRes.tempFilePaths[0],
							name: 'file',
							success: (uploadFileRes) => {
								const fileData = uploadFileRes.data ? JSON.parse(uploadFileRes
									.data) : ''
								if (fileData && fileData.code == 200) {
									this.recordList.files.push({
										id: fileData.data.id,
										temp: chooseImageRes.tempFilePaths[0]
									})
									uni.showToast({
										title: '上传成功',
										icon: 'none'
									})
								}
							}
						});
					}
				});
			},

			// 删除已上传的图片
			fileDel(index) {
				this.recordList.files.splice(index, 1)
			},

			// 把查询到的每个项目的结果、记录项进行分组处理
			initGroup(list) {
				const res = [];
				const arr = [];
				list.forEach((item) => {
					let index = arr.indexOf(item.dictGroup);
					if (index === -1) {
						arr.push(item.dictGroup);
						index = arr.length - 1;
						res[index] = {
							checked: "",
							children: [],
						};
					}
					if (item.selected) {
						res[index].checked = item.dictKey;
					}
					res[index].children.push(item);
				});
				return res;
			},

			//初始化表格 
			initTable(tableData) {
				tableData = deepClone(tableData);
				let PTI = 0;
				tableData.forEach((item, i) => {
					const prev = tableData[PTI];
					item.inspResult = this.initGroup(item.inspResult);
					// item.inspRecord = this.initGroup(item.inspRecord);
					if (prev.inspItemCode === item.inspItemCode) {
						if (prev.rowspan) {
							prev.rowspan += 1;
						} else {
							prev.rowspan = 1;
						}
					} else {
						PTI = i;
						item.rowspan = 1;
					}
				});
				return tableData;
			},

			// 判断当前页数据是否都勾选了
			isCompleted(list) {
				let itemStatus = true;
				list.forEach((items) => {
					items.inspResult.forEach((item) => {
						if (item.checked === "") {
							itemStatus = false;
						}
					});
				});
				return itemStatus;
			},
		},
	}
</script>

<style lang="scss" scoped>
	.progressBar {
		padding: 20rpx;
	}

	.topic {
		padding: 20rpx 40rpx;
		border-bottom: 1px #F1F1F1 solid;

		.topic_index {
			width: 50rpx;
			height: 50rpx;
			line-height: 50rpx;
			text-align: center;
			border-radius: 50%;
			display: inline-block;
			background-color: #1590EF;
			color: white;
			margin: 0 30rpx 0 0;
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
		}
	}

	.topic_title {
		display: block;
		margin: 30rpx 0;
		border-left: 2px #1590EF solid;
		padding: 0 20rpx;
	}

	.topic_trouble {
		padding: 20px 20px;
		// display: inline-block;
	}


	.submit {
		width: 50%;
		position: fixed;
		bottom: 15px;
		left: 50%;
		transform: translateX(-50%);
	}

	.file-list {
		flex: 1;

		.file-item {
			float: left;
			width: 22%;
			text-align: center;
			height: 140rpx;
			line-height: 140rpx;
			margin-right: 4%;
			margin-bottom: 2%;
			position: relative;

			.file-img {
				max-width: 100%;
				max-height: 100%;
				vertical-align: middle;
			}

			.file-del {
				position: absolute;
				right: 0;
				top: 0;
				transform: translate(30%, -30%);
				border-radius: 50%;
				width: 0;
				height: 0;
				border: 20rpx solid #f00;

				&::after {
					content: "";
					width: 20rpx;
					display: block;
					transform: translate(-50%, -50%);
					background-color: #ffffff;
					height: 4rpx;
				}
			}

			&:nth-child(4n) {
				margin-right: 0;
			}

			&:nth-child(n+5) {
				margin-top: calc(4% / 3);
			}

		}

		.file-upload-btn {
			box-sizing: border-box;
			border: 1px solid #ddd;
			background: url('/static/img/camera.png') no-repeat center;
			background-size: 70%;
		}
	}
</style>
